package org.jeecg.modules.device;

import org.jeecg.boot.starter.rabbitmq.client.RabbitMqClient;
import org.jeecg.modules.commu.ClientConnection;
import org.jeecg.modules.commu.ConnectionFactory;
import org.jeecg.modules.driver.DeviceDriver;
import org.jeecg.modules.driver.DriverPortocal1_0;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;

/**
 * 设备管理容器
 */
@Component
public class DeviceContainer {
    HashMap<String, TigDeviceShadow> sdDevices = new HashMap<>();

    @Autowired
    RabbitMqClient rabbitMqClient;

    public boolean deviceExist(String deviceId){
        return sdDevices.containsKey(deviceId);
    }

    /**
     * 连接成功才会创建成功
     * @param device
     * @return
     */
    public TigDeviceShadow createDeviceShadow(Device device) {
        try {
            TigDeviceShadow sd = new TigDeviceShadow(device, null,rabbitMqClient);
            if(sd.connect()){
                //连接成功就加上去管理
                addShadowDevice(sd);
                return sd;
            }
            else{
                addShadowDevice(sd);
                return null;
            }
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    public TigDeviceShadow getShadowDevice(String deviceId) {
        return sdDevices.get(deviceId);
    }

    public synchronized void addShadowDevice(TigDeviceShadow sd){
        sdDevices.put(sd.getDevice().getId(), sd);
    }

    public synchronized void removeDevice(TigDeviceShadow device) {
        sdDevices.remove(device.getDevice().getId());
    }
}
